package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "/user")
public class UserController {


     @Reference
    private UserService userService;

    /**
     * 获取当前登录用户的用户名
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUsername")
    public Result getUsername() throws Exception {
        try {
            UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, userDetails.getUsername());
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    /**
     * 分页查询检查项数据
     * @param pageBean
     * @return
     */
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean pageBean){
        return userService.findPage(pageBean);
    }

    /**
     * 查询所有角色
     * @param
     * @return
     */
    //查询所有角色
   /* @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<User> list = userService.findAll();
            return new Result(true, "查找用户成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查找用户失败");
        }
    }*/

  /**
     * 新增角色
     * @param user
     * @return
     */
    @RequestMapping(path = "/add")
    public Result add(@RequestBody User user){
        try {
            userService.add(user);
            return new Result(true,MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_CHECKITEM_FAIL);
        }
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping(path = "/{id}")
    public Result deleteById(@PathVariable Integer id){
        try {
            userService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }
}
